<template>
  <div class="edit">
      <h2>{{$route.query.id?'修改地址':'添加地址'}}</h2>
      <van-address-edit
        :area-list="areaList"
        show-delete
        show-set-default
        show-search-result
        :search-result="searchResult"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
        @delete="onDelete"
        @change-detail="onChangeDetail"
        :address-info="addressInfo"
      />
  </div>
</template>

<script>
import area from '../../../../../assets/json/city'
import {getAddressItem, updateAddress, delAddress, addAddress } from '@/api/api'
export default {
  data() {
    return {
      areaList:area,
      searchResult: [],
      addressInfo:{}
    };
  },
  //编辑  要回显
  created(){
    if(this.$route.query.id){
      getAddressItem(this.$route.query.id).then(res => {
        if (res.code === 200) {
          console.log(res.data[0])
          this.addressInfo = res.data[0]
          this.addressInfo.addressDetail = res.data[0].address
          /* eslint-disable */
          this.addressInfo.isDefault = this.addressInfo.isDefault ? true : false
          /* eslint-disable */
        }
      })
    }
  },
  methods: {
    //点击 添加 或者修改
    onSave(e) {
      console.log(e)
      e.address = e.addressDetail
      e.area = e.country
      if (this.$route.query.id) {
        updateAddress(e).then(res => {
          if (res.code === 200) {
            this.$toast.success('修改成功')
            this.$router.push('/home/mine/address')
          }
        })
      } else {
        addAddress(e).then(res => {
          if (res.code === 200) {
            this.$toast.success('添加成功')
            this.$router.push('/home/mine/address')
          }
        })
      }
    },
    onDelete() {
      //删除一波
      delAddress(this.$route.query.id).then(res => {
        if(res.code === 200) {
          this.$toast.success('删除成功')
        }
      })
      this.$router.push('/patient/address')
    },
    onChangeDetail(val) {
      if (val) {
        this.searchResult = [
          {
            name: '黄龙万科中心',
            address: '杭州市西湖区',
          },
        ];
      } else {
        this.searchResult = [];
      }
    },
  },
}
</script>

<style>
.edit{
    width: 100%;
    height: 100%;
}
</style>